<?php
declare (strict_types=1);

namespace app\exam\model\admin;

use app\common\logic\Attach;
use app\common\model\BaseModel;
use think\model\concern\SoftDelete;

/**
 * Class Module
 *
 * @package app\exam\model\admin
 */
class Module extends BaseModel
{
    use SoftDelete;

    /**
     * 表名
     *
     * @var string
     */
    protected $name = 'exam_module';

    /**
     * 自动写入时间
     *
     * @var bool
     */
    protected $autoWriteTimestamp = true;

    /**
     * 不需要创建时间
     *
     * @var bool
     */
    protected $createTime = false;

    /**
     * 定义字段类型
     *
     * @var array
     */
    protected $type = [
        'id'               => 'integer'
    ];

    /**
     * 全局查询范围
     *
     * @var [type]
     */
    protected $globalScope = ['mhm'];

    /**
     * 限制机构条件
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/12/21
     *
     * @param $query
     */
    public function scopeMhm($query)
    {
        // 机构
        $query->where('mhm_id', request()->mhm_id);
    }

    /**
     * 分类数据
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/03/11
     *
     * @param $category
     * @param $data
     * @return string
     */
    public function setCategoryAttr($category): ?string
    {
        if (is_string($category) || is_null($category) || !is_array($category)) return $category;
        return $category ? ',' . implode(',', array_unique($category)) . ',' : '';
    }

    /**
     * 新增数据事件
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-14
     *
     */
    public static function onBeforeInsert($model)
    {
        // 机构
        $model->mhm_id = $model->getAttr('mhm_id') ?: request()->mhm_id;
    }

    /**
     * 定义版块属性
     *
     * @var string[]
     */
    protected $moduleType = [
        1 => '知识点练习',
        2 => '专项练习',
        3 => '公开考试',
        4 => '套卷练习'
    ];

    /**
     * @return string[]
     */
    public function getModuleType(): array
    {
        return $this->moduleType;
    }

    /**
     * 获取版块类型名称
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/1/26
     *
     * @param $value
     * @param $data
     * @return string
     */
    public function getModuleTypeTextAttr($value, $data)
    {
        $text = $this->getModuleType();

        return $text[$data['module_type']] ?? '未知';
    }

    /**
     * 定义版块状态
     *
     * @var string[]
     */
    protected $statusList = [
        0 => '禁用',
        1 => '启用'
    ];

    /**
     * @return string[]
     */
    public function getStatusList(): array
    {
        return $this->statusList;
    }

    /**
     * 封面图
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/2/3
     *
     * @return \think\model\relation\BelongsTo
     */
    public function coverUrl()
    {
        return $this->belongsTo(Attach::class, 'cover', 'id')->bind(['cover_url' => 'fileurl']);
    }

}